package main

import (
	"flag"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strconv"

	"github.com/golang/glog"
)

func main() {
	flag.Set("v", "4")
	glog.V(2).Info("Starting http server...")

	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/env", getEnvHander)
	http.HandleFunc("/healthz", healthzHandler)
	error := http.ListenAndServe(":80", nil)
	if error != nil {
		glog.Fatalln(error)
	}

}

/**
http://localhost:80/
*/
func indexHandler(w http.ResponseWriter, r *http.Request) {
	// for k, v := range r.Header {
	// 	fmt.Println(k, "=", v)
	// 	fmt.Fprintf(w, "%s=%s\n", k, v)
	// }
	var statusCode int
	var url string
	value, ok := r.Header["Referer"]
	if ok {
		url = value[0]
		// fmt.Println(value[0])
		statusCode = getUrlCode(value[0])
	}

	//状态码转换成字符串
	var codes string
	if statusCode == 200 {
		codes = "200 OK"
	} else {
		codes = strconv.Itoa(statusCode)
	}
	// 记录访问IP 状态码 访问server的客户端信息
	s := getIP(r)
	fmt.Printf("URL-->:〖%s〗 ┃ IP-->:〖%s〗┃ Status-Code-->:〖%s〗┃ User-Agent-->: %s\r\n ", url, s, codes, r.Header["User-Agent"])

}

//获取客户端真实IP
func getIP(r *http.Request) (ip string) {
	forwarded := r.Header.Get("X-FORWARDED-FOR")

	if forwarded == "" {
		forwarded = r.RemoteAddr
	}
	ip = forwarded[1:4]
	if ip == "::1" {
		ip = "127.0.0"
	}
	return ip

}

// 判断http返回的状态码
func getUrlCode(urls string) int {
	u, _ := url.Parse(urls)
	q := u.Query()
	u.RawQuery = q.Encode()
	res, err := http.Get(u.String())
	if err != nil {
		fmt.Println("0")
		return 0
	}
	resCode := res.StatusCode
	res.Body.Close()
	if err != nil {
		fmt.Println("0")
		return 0
	}
	return resCode
}

/**
http://localhost:80/healthz
*/
func healthzHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "200\n")

}

/*
http://localhost:80/env
*/
func getEnvHander(w http.ResponseWriter, r *http.Request) {
	envs := "HOME"
	version := os.Getenv(envs)
	fmt.Fprintf(w, "环境变量%s:%s\n", envs, version)
}
